import {defineStore} from 'pinia'
import {ref} from 'vue'
import {defaultLoading, defaultResArray} from '@/store/main/config'
import {cloudGeneralObject} from '@/uniCloud-alipay'
import {checkImgAndExtract} from '@/utils/check-obj'

const useMainStore = defineStore('main', () => {
  //结果数组
  const resArray = ref(defaultResArray)
  //加载状态
  const isLoading = ref(defaultLoading)
  //分类数组
  const catagoryArr = ref(defaultResArray)

  //获取列表
  const fetchListAction = async (table) => (await cloudGeneralObject.getList(table)).data

  //获取数据
  const fetchHomeDataAction = async () => {
  }

  //获取结果
  const fetchResArrayAction = async (table) => {
    isLoading.value = true
    resArray.value = await fetchListAction(table)
    isLoading.value = false
  }

  //编辑数据
  const fetchEditAction = async (table, id, data, afterFetchData = true) => {
    //检测图片
    await checkImgAndExtract(data, table)
    await cloudGeneralObject.updateDataById(table, id, data)
    afterFetchData && await fetchResArrayAction(table)
  }

  //新增数据
  const fetchAddAction = async (table, data, afterFetchData = true) => {
    //检测图片
    await checkImgAndExtract(data, table)
    const res = await cloudGeneralObject.insertData(table, data)
    if (afterFetchData) await fetchResArrayAction(table)

    //返回新增结果
    return res
  }

  //删除数据
  const fetchDeleteAction = async (table, id) => {
    await cloudGeneralObject.deleteDataById(table, [id])
    await fetchResArrayAction(table)
  }

  //根据字段删除
  const fetchDeleteByFieldAction = async (table, field, value, afterFetchData = true) => {
    await cloudGeneralObject.deleteDataByField(table, field, value)
    afterFetchData && await fetchResArrayAction(table)
  }

  //根据字段获取信息
  const fetchGetDetailAction = async (table, field, value) => {
    return (await cloudGeneralObject.getListByField(table, field, value)).data
  }

  return {
    resArray,
    isLoading,
    catagoryArr,
    fetchListAction,
    fetchHomeDataAction,
    fetchResArrayAction,
    fetchEditAction,
    fetchAddAction,
    fetchDeleteAction,
    fetchDeleteByFieldAction,
    fetchGetDetailAction
  }
})

export default useMainStore
